<template>
  <u-popup
    :show="show"
    mode="center"
    round="0"
    :closeable="false"
    @close="close"
    :safeAreaInsetBottom="true"
	bgColor="transparent"
  >
    <view class="poster-container">      
      <!-- 海报预览区域 -->
      <view class="poster-preview">
        <!-- Swiper轮播 -->
        <swiper
          class="poster-swiper"
          :current="currentIndex"
          @change="onSwiperChange"
          :circular="true"
          :autoplay="false"
        >
          <swiper-item
            v-for="(bg, index) in backgroundList"
            :key="index"
            class="swiper-item"
          >
            <!-- 直接使用html2canvas组件，通过ref获取实例 -->
            <sp-html2canvas-render 
              :ref="`h2c-${index}`"
              :domId="`poster-${index}`"
              @renderOver="onRenderOver"
            >
              <!-- 海报内容 -->
              <view :id="`poster-${index}`" class="poster-content">
                <!-- 背景图片 -->
                <image
                  :src="bg || defaultBg"
                  mode="aspectFit"
                  class="poster-bg"
                />
                
                <!-- 二维码 -->
                <view class="qrcode-container" v-if="qrcode">
                  <image
                    :src="qrcode"
                    mode="widthFix"
                    class="qrcode-image"
                  />
                </view>
              </view>
            </sp-html2canvas-render>
          </swiper-item>
        </swiper>
        
        <!-- 指示器 -->
        <view class="swiper-indicator">
          <view
            v-for="(bg, index) in backgroundList"
            :key="index"
            class="indicator-dot"
            :class="{ active: currentIndex === index }"
            @click="switchPoster(index)"
          ></view>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="poster-actions">
        <button class="btn-save" @click="savePoster" :disabled="saving">
          <text v-if="saving">生成中...</text>
          <text v-else>保存到相册</text>
        </button>
      </view>
      
      <!-- 保存提示 -->
      <u-toast ref="uToast"></u-toast>
    </view>
  </u-popup>
</template>

<script>
// 引入您现有的html2canvas组件
import SpHtml2canvasRender from '@/uni_modules/sp-html2canvas-render/components/sp-html2canvas-render/sp-html2canvas-render.vue';

export default {
  name: 'CreatePoster',
  components: {
    SpHtml2canvasRender
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    qrcode: {
      type: String,
      default: ''
    },
    backgroundList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      currentIndex: 0,
      saving: false,
      defaultBg: ''
    };
  },
  watch: {
    show(newVal) {
      if (newVal) {
        this.initPoster();
      }
    }
  },
  methods: {
    initPoster() {
      this.currentIndex = 0;
      this.saving = false;
    },
    
    onSwiperChange(e) {
      this.currentIndex = e.detail.current;
    },
    
    switchPoster(index) {
      this.currentIndex = index;
    },
    
    // 获取当前html2canvas实例
    getCurrentH2CInstance() {
      const refName = `h2c-${this.currentIndex}`;
      return this.$refs[refName];
    },
    
    // 保存海报
    async savePoster() {
      if (this.saving) return;
      
      this.saving = true;
      
      try {
        uni.showLoading({
          title: '生成海报中...',
          mask: true
        });
        
        // 等待一下确保组件渲染完成
        await this.$nextTick();
        
        // 获取当前html2canvas实例
        const h2cInstance = this.getCurrentH2CInstance();
        
        console.log('h2cInstance:', h2cInstance); // 调试用
        
        if (h2cInstance && h2cInstance[0] && typeof h2cInstance[0].renderDom === 'function') {
          // 触发渲染
          h2cInstance[0].renderDom();
        } else {
          throw new Error('海报生成组件未就绪，请稍后重试');
        }
        
      } catch (error) {
        console.error('保存海报失败:', error);
        uni.hideLoading();
        this.saving = false;
        
        this.$refs.uToast.show({
          message: error.message || '生成失败，请重试',
          type: 'error',
          duration: 2000
        });
      }
    },
    
    // 渲染完成回调
    onRenderOver(base64Data) {
      uni.hideLoading();
      this.saving = false;
      
      console.log('渲染完成，base64数据长度:', base64Data ? base64Data.length : 0);
      
      if (base64Data && base64Data.startsWith('data:image')) {
        this.saveBase64ToPhotos(base64Data);
      } else {
        this.$refs.uToast.show({
          message: '生成失败，请重试',
          type: 'error',
          duration: 2000
        });
      }
    },
    
    // 将base64保存到相册
    saveBase64ToPhotos(base64Data) {
      // 在H5环境中使用不同的保存方式
      if (typeof window !== 'undefined' && window.navigator) {
        this.saveBase64InH5(base64Data);
      } else {
        this.saveBase64InApp(base64Data);
      }
    },
    
    // 在App中保存base64
    saveBase64InApp(base64Data) {
      const fs = uni.getFileSystemManager();
      const filePath = `${uni.env.USER_DATA_PATH}/temp_poster_${Date.now()}.jpg`;
      
      try {
        // 移除base64前缀
        const base64 = base64Data.replace(/^data:image\/\w+;base64,/, '');
        
        fs.writeFile({
          filePath: filePath,
          data: base64,
          encoding: 'base64',
          success: () => {
            uni.saveImageToPhotosAlbum({
              filePath: filePath,
              success: () => {
                this.showSuccess('海报已保存到相册');
                this.cleanupTempFile(filePath);
              },
              fail: (err) => {
                console.error('保存到相册失败:', err);
                this.showError('保存失败，请检查相册权限');
                this.cleanupTempFile(filePath);
              }
            });
          },
          fail: (err) => {
            console.error('写入临时文件失败:', err);
            this.showError('生成失败');
          }
        });
      } catch (error) {
        console.error('base64转换失败:', error);
        this.showError('生成失败');
      }
    },
    
    // 在H5中保存base64
    saveBase64InH5(base64Data) {
      try {
        const link = document.createElement('a');
        link.download = `poster_${Date.now()}.jpg`;
        link.href = base64Data;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.showSuccess('海报已开始下载');
      } catch (error) {
        console.error('H5下载失败:', error);
        this.showError('下载失败');
      }
    },
    
    // 清理临时文件
    cleanupTempFile(filePath) {
      try {
        const fs = uni.getFileSystemManager();
        fs.unlinkSync(filePath);
      } catch (e) {
        console.log('清理临时文件失败:', e);
      }
    },
    
    // 显示成功提示
    showSuccess(message) {
      this.$refs.uToast.show({
        message: message,
        type: 'success',
        duration: 2000
      });
    },
    
    // 显示错误提示
    showError(message) {
      this.$refs.uToast.show({
        message: message,
        type: 'error',
        duration: 2000
      });
    },
    
    close() {
      this.$emit('update:show', false);
      this.$emit('close');
    }
  }
};
</script>

<style lang="less" scoped>
.poster-container {
  width: 90vw;
  max-width: 1000rpx;
  overflow: hidden;
}


.poster-swiper {
  height: 600rpx;
  overflow: hidden;
}

.swiper-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.poster-content {
  width: 1000rpx;
  height: 1000rpx;
  position: relative;
  overflow: hidden;
}

.poster-bg {
  width: 100%;
  height: 100%;
}

.qrcode-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
}

.qrcode-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  background: #fff;
  padding: 8rpx;
  box-sizing: border-box;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.3);
}

.swiper-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top:10px;
}

.indicator-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #ddd;
  margin: 0 6rpx;
  transition: all 0.3s;
  cursor: pointer;
  
  &.active {
    background: #007aff;
    width: 24rpx;
    border-radius: 6rpx;
  }
}

.poster-actions {
  padding: 30rpx;
  
  .btn-save {
    width: 100%;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    background: linear-gradient(135deg, #007aff, #0056cc);
    color: #fff;
    border: none;
    
    &:after {
      border: none;
    }
    
    &[disabled] {
      background: #ccc;
      color: #999;
    }
  }
}
</style>